#!/usr/bin/env python3
"""
开发环境启动脚本
安装依赖、初始化数据库、启动服务
"""
import os
import sys
import subprocess
import asyncio
from pathlib import Path

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

def run_command(command: str, cwd: str = None) -> bool:
    """
    运行命令
    Args:
        command: 要执行的命令
        cwd: 工作目录
    Returns:
        是否成功
    """
    print(f"执行命令: {command}")
    try:
        result = subprocess.run(
            command,
            shell=True,
            cwd=cwd,
            check=True,
            capture_output=True,
            text=True
        )
        print(f"✓ 命令执行成功")
        if result.stdout:
            print(result.stdout)
        return True
    except subprocess.CalledProcessError as e:
        print(f"✗ 命令执行失败: {e}")
        if e.stdout:
            print("STDOUT:", e.stdout)
        if e.stderr:
            print("STDERR:", e.stderr)
        return False

def check_dependencies():
    """检查Python依赖"""
    print("检查Python依赖...")
    
    required_packages = [
        "fastapi", "uvicorn", "sqlalchemy", "alembic", 
        "pydantic", "pytest", "structlog"
    ]
    
    missing_packages = []
    for package in required_packages:
        try:
            __import__(package)
            print(f"✓ {package} 已安装")
        except ImportError:
            print(f"✗ {package} 未安装")
            missing_packages.append(package)
    
    return len(missing_packages) == 0

def install_dependencies():
    """安装Python依赖"""
    print("安装Python依赖...")
    
    backend_dir = Path(__file__).parent
    requirements_file = backend_dir / "requirements.txt"
    
    if not requirements_file.exists():
        print(f"✗ requirements.txt 文件不存在: {requirements_file}")
        return False
    
    return run_command(f"pip install -r {requirements_file}", cwd=str(backend_dir))

def initialize_database():
    """初始化数据库"""
    print("初始化数据库...")
    
    backend_dir = Path(__file__).parent
    
    # 检查alembic.ini是否存在
    alembic_ini = backend_dir / "alembic.ini"
    if not alembic_ini.exists():
        print("✗ alembic.ini 文件不存在")
        return False
    
    # 检查alembic目录是否存在
    alembic_dir = backend_dir / "alembic"
    if not alembic_dir.exists():
        print("初始化alembic...")
        if not run_command("alembic init alembic", cwd=str(backend_dir)):
            return False
    
    # 创建初始迁移
    print("创建初始数据库迁移...")
    if not run_command('alembic revision --autogenerate -m "Initial migration"', cwd=str(backend_dir)):
        print("迁移创建失败，这可能是正常的（如果数据库已经是最新的）")
    
    # 执行迁移
    print("执行数据库迁移...")
    return run_command("alembic upgrade head", cwd=str(backend_dir))

def run_tests():
    """运行测试"""
    print("运行测试...")
    
    backend_dir = Path(__file__).parent
    return run_command("python -m pytest tests/ -v", cwd=str(backend_dir))

def start_development_server():
    """启动开发服务器"""
    print("启动开发服务器...")
    
    backend_dir = Path(__file__).parent
    
    # 启动服务器
    print("启动FastAPI开发服务器...")
    print("服务器将在 http://localhost:8000 上运行")
    print("API文档: http://localhost:8000/api/v1/docs")
    print("按 Ctrl+C 停止服务器")
    
    os.chdir(backend_dir)
    os.system("python -m uvicorn main:app --reload --host 0.0.0.0 --port 8000")

def main():
    """主函数"""
    print("=== SmartCity-LLM Trainer 开发环境启动 ===")
    
    # 检查是否在正确的目录
    backend_dir = Path(__file__).parent
    if not (backend_dir / "main.py").exists():
        print("✗ 未找到main.py文件，请确保在backend目录中运行此脚本")
        sys.exit(1)
    
    # 步骤1: 检查依赖
    if not check_dependencies():
        print("\n步骤1: 安装依赖")
        if not install_dependencies():
            print("✗ 依赖安装失败")
            sys.exit(1)
        print("✓ 依赖安装成功")
    else:
        print("✓ 所有依赖都已安装")
    
    # 步骤2: 初始化数据库
    print("\n步骤2: 初始化数据库")
    if initialize_database():
        print("✓ 数据库初始化成功")
    else:
        print("⚠ 数据库初始化失败，但继续启动服务器")
    
    # 步骤3: 运行测试（可选）
    run_tests_choice = input("\n是否运行测试？(y/N): ").lower().strip()
    if run_tests_choice in ['y', 'yes']:
        print("\n步骤3: 运行测试")
        if run_tests():
            print("✓ 测试通过")
        else:
            print("⚠ 测试失败，但继续启动服务器")
    
    # 步骤4: 启动开发服务器
    print("\n步骤4: 启动开发服务器")
    try:
        start_development_server()
    except KeyboardInterrupt:
        print("\n\n=== 服务器已停止 ===")

if __name__ == "__main__":
    main()